package com.ddch.udpsocket.socket;

import android.content.Context;
import android.os.Handler;
import android.text.TextUtils;

import com.ddch.udpsocket.common.Config;
import com.ddch.udpsocket.listener.OnConnectionStateListener;
import com.ddch.udpsocket.listener.OnMessageReceiveListener;
import com.ddch.udpsocket.socket.tcp.TCPSocket;
import com.ddch.udpsocket.socket.udp.UDPSocket;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * created by 韦敏敏
 * on 2019/12/23
 */
public class SocketManager {
    private static volatile  SocketManager instance = null;
    private UDPSocket udpSocket;
    private TCPSocket tcpSocket;
    private Context mContext;
    private static Handler mHandler;
    private SocketManager(Context context, Handler handler){
        mContext = context.getApplicationContext();
        this.mHandler = handler;
    }
    public static SocketManager getInstance(Context context, Handler handler){
        // if already inited,no need to get lock everytime
        if(instance == null){
            synchronized (SocketManager.class){
                if(instance == null){
                    instance = new SocketManager(context, handler);
                }
            }
        }
        return instance;
    }
    // 启动UDP连接
    public void  startUdpConnection(){
        if(udpSocket == null){
            udpSocket = new UDPSocket(mContext);
        }
        // 注册接收消息的接口
        udpSocket.addOnMessageReceiveListener(new OnMessageReceiveListener() {
            @Override
            public void onMessageReceived(String msg) {
                handleUdpMessage(msg);
            }
        });
        udpSocket.startUDPSocket(mHandler);
    }

    /**
     * 处理UDP收到的消息
     * @param msg
     */
    private void handleUdpMessage(String msg) {
        try {
            JSONObject jsonObject = new JSONObject(msg);
            String ip = jsonObject.optString(Config.TCP_IP);
            String port = jsonObject.optString(Config.TCP_PORT);
            if(!TextUtils.isEmpty(ip) && !TextUtils.isEmpty(port)){
                // 开启tcp连接
                startTcpConnection(ip, port);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }


    }

    /**
     * 开始 TCP 连接
     * @param ip
     * @param port
     */
    private void startTcpConnection(String ip, String port) {
        // 保证收到消息后，只创建一次
        if(tcpSocket == null){
            tcpSocket = new TCPSocket(mContext);
            tcpSocket.startTcpSocket(ip, port);
            tcpSocket.setOnConnectionStateListener(new OnConnectionStateListener() {
                @Override
                public void onSuccess() {
                    // tcp  创建成功
                    udpSocket.stopHeartbeatTimer();
                }
                @Override
                public void onFailed(int errorCode) {
                    // tcp异常
                    switch (errorCode){
                        case Config.ErrorCode.CREATE_TCP_ERROR:
                            break;
                        case Config.ErrorCode.PING_TCP_TIMEOUT:
                            udpSocket.startHeartbeatTimer();
                            tcpSocket = null;
                            break;
                        default:
                            break;

                    }

                }
            });
        }
    }
    public void stopSocket(){
        udpSocket.stopUDPSocket();
        tcpSocket.stopTcpConnection();
        if(udpSocket != null)
            udpSocket = null;
        if(tcpSocket != null)
            tcpSocket = null;
    }

}
